package org.windowkit.toolkit;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import org.ddevil.data.Data;

/**
 * @author Rich O'Connell
 */
public abstract class Worker implements Runnable {
	private final List<WorkListener> listeners;
	private Data results;

	public Worker(final WorkListener ...listenerList) {
		listeners = new ArrayList<WorkListener>();
		for (WorkListener wl : listenerList) {
			listeners.add(wl);
		}
	}

	public void addListener(final WorkListener wl) {
		listeners.add(wl);
	}

	public void removeListener(final WorkListener wl) {
		listeners.remove(wl);
	}

	public Data getResults() {
		return results;
	}

	protected void setResults(final Data results) {
		this.results = results;
	}

	/**
	 * {@inheritDoc}
	 */
	public void run() {
		doWork();
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				for (WorkListener wl : listeners) {
					wl.workComplete(Worker.this);
				}
			}
		});
	}

	protected abstract void doWork();

	public interface WorkListener {
		void workComplete(Worker worker);
	}

}
